package com.mapaoer.user.controller;

import com.mapaoer.user.dto.DeveloperProfileDTO;
import com.mapaoer.user.entity.User;
import com.mapaoer.user.service.DeveloperProfileService;
import com.mapaoer.user.service.UserService;
import com.mapaoer.user.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 开发者资料控制器
 * 处理开发者资料相关的API请求
 */
@RestController
@RequestMapping("/api/developer")
public class DeveloperProfileController {

    @Autowired
    private DeveloperProfileService developerProfileService;

    @Autowired
    private UserService userService;

    /**
     * 创建开发者资料
     * @param developerProfileDTO 开发者资料
     * @return 创建结果
     */
    @PostMapping("/profile")
    @PreAuthorize("hasRole('DEVELOPER')")
    public ResponseEntity<ResponseResult<?>> createDeveloperProfile(@Valid @RequestBody DeveloperProfileDTO developerProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        developerProfileDTO.setUserId(user.getId());
        boolean result = developerProfileService.createDeveloperProfile(developerProfileDTO);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("开发者资料创建成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("开发者资料已存在"));
        }
    }

    /**
     * 更新开发者资料
     * @param developerProfileDTO 开发者资料
     * @return 更新结果
     */
    @PutMapping("/profile")
    @PreAuthorize("hasRole('DEVELOPER')")
    public ResponseEntity<ResponseResult<?>> updateDeveloperProfile(@Valid @RequestBody DeveloperProfileDTO developerProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        DeveloperProfileDTO existingProfile = developerProfileService.getDeveloperProfileByUserId(user.getId());
        if (existingProfile == null) {
            return ResponseEntity.notFound().build();
        }
        
        boolean result = developerProfileService.updateDeveloperProfile(existingProfile.getId(), developerProfileDTO);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("开发者资料更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("开发者资料更新失败"));
        }
    }

    /**
     * 获取当前登录开发者的资料
     * @return 开发者资料
     */
    @GetMapping("/profile")
    @PreAuthorize("hasRole('DEVELOPER')")
    public ResponseEntity<ResponseResult<?>> getCurrentDeveloperProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        DeveloperProfileDTO profile = developerProfileService.getDeveloperProfileByUserId(user.getId());
        if (profile != null) {
            return ResponseEntity.ok(ResponseResult.success(profile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取指定ID的开发者资料
     * @param id 开发者资料ID
     * @return 开发者资料
     */
    @GetMapping("/profile/{id}")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> getDeveloperProfileById(@PathVariable Long id) {
        DeveloperProfileDTO profile = developerProfileService.getDeveloperProfileById(id);
        if (profile != null) {
            return ResponseEntity.ok(ResponseResult.success(profile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 搜索开发者
     * @param skills 技能
     * @param minExperience 最小工作年限
     * @param workType 工作类型
     * @param minAge 最小年龄
     * @param maxAge 最大年龄
     * @return 开发者列表
     */
    @GetMapping("/search")
    @PreAuthorize("hasAnyRole('ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> searchDevelopers(
            @RequestParam(required = false) String skills,
            @RequestParam(required = false) Integer minExperience,
            @RequestParam(required = false) String workType,
            @RequestParam(required = false) Integer minAge,
            @RequestParam(required = false) Integer maxAge) {
        List<DeveloperProfileDTO> developers = developerProfileService.searchDevelopers(
                skills, minExperience, workType, minAge, maxAge);
        return ResponseEntity.ok(ResponseResult.success(developers));
    }

    /**
     * 添加技能
     * @param skillName 技能名称
     * @param level 熟练程度
     * @param experienceYears 使用年限
     * @return 添加结果
     */
    @PostMapping("/skills")
    @PreAuthorize("hasRole('DEVELOPER')")
    public ResponseEntity<ResponseResult<?>> addSkill(
            @RequestParam String skillName,
            @RequestParam String level,
            @RequestParam(required = false) Integer experienceYears) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        DeveloperProfileDTO profile = developerProfileService.getDeveloperProfileByUserId(user.getId());
        if (profile == null) {
            return ResponseEntity.badRequest().body(ResponseResult.error("请先创建开发者资料"));
        }
        
        boolean result = developerProfileService.addSkill(profile.getId(), skillName, level, experienceYears);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("技能添加成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("技能添加失败，可能已存在"));
        }
    }

    /**
     * 删除技能
     * @param skillId 技能ID
     * @return 删除结果
     */
    @DeleteMapping("/skills/{skillId}")
    @PreAuthorize("hasRole('DEVELOPER')")
    public ResponseEntity<ResponseResult<?>> removeSkill(@PathVariable Long skillId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        DeveloperProfileDTO profile = developerProfileService.getDeveloperProfileByUserId(user.getId());
        if (profile == null) {
            return ResponseEntity.badRequest().body(ResponseResult.error("请先创建开发者资料"));
        }
        
        boolean result = developerProfileService.removeSkill(profile.getId(), skillId);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("技能删除成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("技能删除失败"));
        }
    }
}